package com.example.taximeter.controller;

import com.example.taximeter.bean.FileInfo;
import com.example.taximeter.bean.ReturnInfo;
import com.example.taximeter.config.GlobalParam;
import com.example.taximeter.service.FileInfoService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * 文件管理
 */
@RestController
public class FileController extends WebMvcConfigurerAdapter {

    private final FileInfoService fileInfoService;

    @Autowired
    public FileController(FileInfoService fileInfoService){
        this.fileInfoService = fileInfoService;
    }


    /**
     * 部署时候需要修改
     */
    @Value("${file.uploadFolder}")
    private String path;

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + path);
    }

    //查询文件列表信息（所属id）
    @RequestMapping(value = "/files/all/{ownerid}", method = RequestMethod.GET)
    public ReturnInfo findFiles(@PathVariable("ownerid") String ownerid){
        return ReturnInfo.info2(fileInfoService.findfileByOwnerid(ownerid));
    }

    //查询文件信息（文件id）
    @RequestMapping(value = "/files/{fileid}", method = RequestMethod.GET)
    public FileInfo findFile(@PathVariable("fileid") String fileid){
        return fileInfoService.findfileByFileid(fileid);
    }

    //文件上传
    @RequestMapping(value = "/files", method = RequestMethod.POST)
    public ReturnInfo uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest){
//        String classPath = this.getClass().getClassLoader().getResource("").getPath();
//        String path = classPath+"static/";
        path=path.replaceAll("%20"," ");
        String tablename = httpServletRequest.getParameter("tablename");
        String ownerid = httpServletRequest.getParameter("ownerid");
        String fileid = httpServletRequest.getParameter("fileid");
        if (file.isEmpty()) {
            return ReturnInfo.info1("文件为空");
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        String hzm = fileName.substring(fileName.indexOf("."));
        // 文件上传后的路径
        String fileUrl = "files"+"/"+tablename+"/"+ownerid+"/"+ UUID.randomUUID().toString().replaceAll("-","")+hzm;
        File dest = new File(path + fileUrl);
        //创建父文件路径
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {

            FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
            FileInfo fileInfo = new FileInfo(fileid, ownerid, fileName, fileUrl);

            if (fileInfoService.createFile(fileInfo).equals("成功")) {
                if(hzm.equals(".bin")){
                    InputStream ins = file.getInputStream();
                    byte[] buffer=new byte[1024];
                    int len=0;
                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                    while((len=ins.read(buffer))!=-1){
                        bos.write(buffer,0,len);
                    }
                    bos.flush();
                    byte data[] = bos.toByteArray();
                    if(fileInfoService.updateFilecon(fileid,data).equals("成功")){
                        return ReturnInfo.info4("上传成功", fileName, fileUrl);
                    }else {
                        return ReturnInfo.info1("失败1");
                    }
                }
                return ReturnInfo.info4("上传成功", fileName, fileUrl);

            }else {
                return ReturnInfo.info1("失败2");
            }
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return ReturnInfo.info4("上传失败", "", "");
    }

    //文件下载
    @RequestMapping(value = "/files", method = RequestMethod.GET)
    public ReturnInfo downloadFile(HttpServletResponse response, HttpServletRequest request){
        String fileid = request.getParameter("fileid");
        if (fileid != null&&!fileid.equals("")) {
            String classPath = this.getClass().getClassLoader().getResource("").getPath();
//            String path = classPath.substring(0,classPath.indexOf(GlobalParam.filesposition))+"files/";
            String path = classPath+"static/files/";
            path=path.replaceAll("%20"," ");
            FileInfo fileInfo = fileInfoService.findfileByFileid(fileid);
            File file = new File(path, fileInfo.getFileurl());
            String fileName = fileInfo.getFilename();
            try {
                fileName = new String(fileName.getBytes(), "ISO-8859-1");
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            if (file.exists()) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    //文件删除
    @RequestMapping(value = "/files/{fileid}", method = RequestMethod.DELETE)
    public ReturnInfo deleteFile(@PathVariable String fileid){
        if (fileid != null&&!fileid.equals("")) {
            FileInfo fileInfo = fileInfoService.findfileByFileid(fileid);
            String classPath = this.getClass().getClassLoader().getResource("").getPath();
            String path = classPath+"static/files/";
            path=path.replaceAll("%20"," ");
            String b = GlobalParam.deleteF(fileInfo, path).getMessage();
            if(b.equals("删除成功！")){
                fileInfoService.deleteFile(fileid);
            }
            return ReturnInfo.info1(b);
        }else {
            return ReturnInfo.info1("文件目录错误！");
        }
    }

    //文件转移
    public void copyFile(String oldPath, String newPath) {
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        String path = classPath+"static/files/";
        path=path.replaceAll("%20"," ");
        oldPath = path+oldPath;
        newPath = path+newPath;
        File oldfile = new File(oldPath);
        File newfile = new File(newPath);
        System.out.println(oldPath+"   "+newPath);
        try {
            int byteread = 0;
            if (oldfile.exists()) { //文件存在时
                if(!newfile.getParentFile().exists()){
                    newfile.getParentFile().mkdirs();
                }
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ( (byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
                oldfile.delete();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    //文件夹删除
    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list(); //递归删除目录中的子目录下
            assert children != null;
            for (String aChildren : children) {
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete(); // 目录此时为空，可以删除
    }

}
